import os
from config import Config
from util import makeSubmitHtml, trackstr

from stages import (
                    ProblemProcessingException,
                    Initial, 
                    Rip, 
                    Eject,
                    FetchCDId,
                    FetchMusicbrainzData,
                    LocalCDId,
                    Beepstage,
                    ImplyDiscID,
                    LookupDiscId,
                    )

from filestage import (
                       #PrepareDestination, 
                       FinalDestination,
                       #MoveMiscGubbins,
                       RewidFiles,
                       #Tidy,    
                       DeployDirectory,          
                       )

from cddbstage import FetchCDDBId
from discogsstage import FetchCoverArt

from flac import (
                   FlacEncode, 
                   FlacTag, 
                   AddFlacReplayGain, 
                   ShnSplit,                   
                  )

class Shagger:    
    
    def __init__(self):
        #self.discid = mbdisc.readDisc().getId()
        self.musicBrain = None
        self.discid = None
        self.tracks = None
        self.absdir = None
        #self.dir = os.path.join(Config['tempdir'], self.discid)
        '''
        if not os.access( self.dir(), os.F_OK):
            #sledgehammer approach: can't read => dir doesn't exist.
            os.makedirs( self.dir() )
        self.log("Working in %s" % (self.dir()) )
        '''
     
    def dir(self):
        if( self.absdir != None):
            return self.absdir
        else:
            dir = os.path.join(Config['tempdir'], self.discid)
            if not os.access( dir, os.F_OK):
                #sledgehammer approach: can't read => dir doesn't exist.
                os.makedirs( dir )
            return dir
            
    def setTargetPath(self, targetpath):
        self.targetpath = targetpath    
              
    def filename(self, filename):
        return os.path.join(self.dir(), filename)
            
    def trackfilename(self, track, suffix):
        return os.path.join(self.dir(), trackstr(track) + "." + suffix)
    
    def fileSubset(self, suffix = ""):
        allfiles = os.listdir(self.dir())
        files = []
        for file in allfiles:
            #print "%s" % file
            if suffix == "" or file.endswith( "." + suffix ):
                files = files + [os.path.join(self.dir(), file)]
        return files
    
    def getAllStates(self):
        for i in range(self.disc.getFirstTrackNum(), self.disc.getLastTrackNum()):
            self.getState(i)
            
    def getState(self, track):
        list = os.listdir(self.dir())
        for file in list:
            if file.startswith(trackstr(track)):
               print("Found %s" % file)    
    
    def log(self, msg):
        print("[Shagger] %s") % (msg)
    
    def isAShagger(self):
        return True;
    
    def sentinel(self):
        print("last shagger method")
        
    def touch(self, file):
        file = os.path.join(self.dir(), file)
        
        f = open(file, "w")
        f.close()       
    
    def CheckCD(self):
        #This function checks to see if any CD oprations are necessary and fails if they are
        #good for skipping discs where the CD is still necessary.
        LocalCDId(self, self.discid)()
        
        FetchMusicbrainzData(self)();
                
        tracks = self.tracks
        for i in tracks:
            if Initial(self, i).canWork(): raise(ProblemProcessingException( "Track %d missing." % i))
        for i in tracks:
            if Rip(self, i).canWork(): raise(ProblemProcessingException( "Need CD to rip track %d." % i))
    
    def workCD(self):
        
        done = False
        cd = False
        
        try:
            if self.discid == None:
                FetchCDId(self)()
                FetchCDDBId(self)()
                makeSubmitHtml()
                cd = True
            else:
                LocalCDId(self, self.discid)()
            
                    
            try:
                #At this point this stage is optional
                FetchMusicbrainzData(self)()
                Beepstage(self, Beepstage.ok)()
            except ProblemProcessingException, details:
                print("Can't load musicbrainz data\n%s" % details)
                Beepstage(self, Beepstage.error)()    
                     
                
            
            #There's gotta be a better way than this! I'll figure it out eventually.
            #tracks = range(self.disc.getFirstTrackNum(), self.disc.getLastTrackNum()+1)
            tracks = self.tracks
            for i in tracks:
                Initial(self, i)()
            for i in tracks:
                Rip(self, i)()
            
            if cd:
                Eject(self)()
                      
            for i in tracks:
                FlacEncode(self, i)()
                
            #now we really need mb data.
            if not self.musicBrain:
                FetchMusicbrainzData(self)()
            
            for i in tracks:
                FlacTag(self, i)()
            FetchCoverArt(self)()
            AddFlacReplayGain(self)()
            
            #PrepareDestination(self)()
            for i in tracks:
                FinalDestination(self, i)()   
            DeployDirectory(self)()  
            #MoveMiscGubbins(self)()
            #Tidy(self)()
            Beepstage(self, Beepstage.done)()
            done = True
        finally:
            self.log("done.")
            #if not done:
                #Beepstage(self, Beepstage.fail)()
    
    def ReworkTags(self):
        #LookupDiscId(self)()
        i = ImplyDiscID(self)
        if( not i.canWork()):
            return
        i()
        FetchMusicbrainzData(self)()
        ShnSplit(self)()
        RewidFiles(self)()
        tracks = self.tracks
        for i in tracks:
            FlacTag(self, i)()
        FetchCoverArt(self)()
        AddFlacReplayGain(self)()
        
        #PrepareDestination(self)()
        for i in tracks:
            FinalDestination(self, i)()
        DeployDirectory(self)()        
        #MoveMiscGubbins(self)()
        #Tidy(self)()
    
    def Lookup(self):
        LookupDiscId(self)()
               
    def CoverArtOnly(self):
        i = ImplyDiscID(self)
        if( not i.canWork()):
            return
        i()
        FetchCoverArt(self)()
 
